package cos

import (
	"context"
	"github.com/tencentyun/cos-go-sdk-v5"
	"io"
	"net/http"
	"net/url"
	"time"
)

type Service struct {
	client *cos.Client
	sid    string
	skey   string
}

func NewService(addr, sid, skey string) (*Service, error) {
	//addr := "https://coolcar-1302389650.cos.ap-shanghai.myqcloud.com"
	u, err := url.Parse(addr)
	if err != nil {
		panic(err)
	}
	b := &cos.BaseURL{BucketURL: u}
	//sid := "AKIDQbaF7kiNr77wZLeFUYZOySxB9rOGO0uX"
	//skey := "aCVbV8cs0tVu8cyBCxToskcOZeaQ9f2N"
	// 1.永久密钥
	client := cos.NewClient(b, &http.Client{
		Transport: &cos.AuthorizationTransport{
			SecretID:  sid,  // 替换为用户的 SecretId，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
			SecretKey: skey, // 替换为用户的 SecretKey，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
		},
	})
	return &Service{
		client: client,
		sid:    sid,
		skey:   skey,
	}, nil
}

func (s *Service) SignUrl(ctx context.Context, method, path string, timeout time.Duration) (string, error) {
	u, err := s.client.Object.GetPresignedURL(ctx, method, path, s.sid, s.skey, timeout, nil)
	if err != nil {
		return "", err
	}
	return u.String(), nil
}

func (s *Service) Get(ctx context.Context, path string) (io.ReadCloser, error) {
	res, err := s.client.Object.Get(ctx, path, nil)
	var b io.ReadCloser
	if res != nil {
		b = res.Body
	}
	if err != nil {
		return b, err
	}
	if res.StatusCode >= 400 {
		return b, err
	}
	return b, nil
}
